<template>
	<a-spin class="inline-flex" :spinning="isUpload">
		<a-upload style="display: flex;" :list-type="isSingleMore?'picture-card':'text'" :fileList="fileList"
			:accept="`.${fileTypes.join(',.')}`" :before-upload="beforeUpload" :show-upload-list="false"
			:disabled="isUpload" v-bind="options" :multiple="true" @change="handleChange">
			<slot />
		</a-upload>
	</a-spin>
</template>
<script>
	import axios from 'axios'
	import {
		debounce
	} from 'lodash'
	import {
		getUpload
	} from '@/api/newPet'
	import {
		ACCESS_TOKEN
	} from '@/store/mutation-types'
	import storage from '@/utils/storage'

	function getSuffix(filename) {
		const pos = filename.lastIndexOf('.')
		let suffix = ''
		if (pos !== -1) {
			suffix = filename.substring(pos)
		}
		return suffix
	}

	function randomString(len) {
		const date = new Date()
		len = len || 20
		var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
		var maxPos = chars.length
		var pwd = ''
		Array.from({
			length: len
		}).forEach(() => {
			pwd += chars.charAt(Math.floor(Math.random() * maxPos))
		})
		return `${pwd}${date.getFullYear()}${date.getMonth() + 1}${date.getDate()}${date.getHours()}${date.getMinutes()}${date.getSeconds()}`
	}

	function getContentType(suffix) {
		if (suffix === '.bmp') {
			return 'image/bmp'
		}
		if (suffix === '.gif') {
			return 'image/gif'
		}
		if (suffix === '.jpeg' ||
			suffix === '.jpg' ||
			suffix === '.png') {
			return 'image/jpg'
		}
		if (suffix === '.html') {
			return 'text/html'
		}
		if (suffix === '.txt') {
			return 'text/plain'
		}
		if (suffix === '.vsd') {
			return 'application/vnd.visio'
		}
		if (suffix === '.pptx' ||
			suffix === '.ppt') {
			return 'application/vnd.ms-powerpoint'
		}
		if (suffix === '.docx' ||
			suffix === '.doc') {
			return 'application/msword'
		}
		if (suffix === '.xml') {
			return 'text/xml'
		}
		return undefined
	}

	export default {
		name: 'Upload',
		props: {
			isSingleMore: {
				type: Boolean,
				default: false
			},
			fileSize: {
				type: Number,
				default: 3
			},
			parallel: {
				type: Number,
				default: 3
			},
			partSize: {
				type: Number,
				default: 4
			},
			thumbnailPathWidth: { // 缩略图宽度
				type: Number,
				default: 100
			},
			thumbnailPathMode: { // 缩略图缩放模式
				type: String,
				default: 'fit'
			},
			fileTypes: {
				type: Array,
				default: () => ['png', 'jpeg', 'gif', 'jpg', 'webp', 'mp4']
			},
			//会员类型1
			scene: {
				type: Number,
				default: 3
			},
			options: {
				type: Object,
				default: () => ({})
			}
		},
		data() {
			return {
				isUpload: false,
				timer: null,
				seconds: 0,
				bucketDomain: '',
				filePath: '',
				ossClient: null,
				fileList: [],
				previewVisible: false,
				previewImage: '',
				isHandlingFiles: false,
				isUploading: false,
				hasUploaded: false, // 添加一个标志变量来控制是否已经上传过

			}
		},
		created() {},
		methods: {
			beforeUpload(file, fileList) {
				const fileSize = this.fileSize
				// if (file.size > 1024 * 1024 * fileSize) {
				//   this.$message.error(`不支持上传大于${fileSize}M的文件`)
				//   this.isUpload = false
				//   this.fileList = []
				//   return false
				// }
				const fileTypes = this.fileTypes
				const fileTypesReg = new RegExp(`.(${this.fileTypes.join('|')})$`, 'i')
				// if (!fileTypesReg.test(file.name)) {
				//   this.$message.error(`只能上传${fileTypes.join(',')}格式的文件`)
				//   this.isUpload = false
				//   this.fileList = []
				//   return false
				// }
				this.fileList = fileList
				console.log(file, fileList)
				this.debounceUpload(file);
				return false
			},

			debounceUpload: debounce(function(file) {

				this.getUpload(file)
			}, 800), // 这里的 300 是防抖的延迟时间，你可以根据实际情况调整


			async getUpload(file) {
				const suffix = getSuffix(file.name)
				try {
					const formData = new FormData();
					// formData.append('path', file.name);
					formData.append('file', file);
					// 发送 POST 请求来上传文件
					const response = await axios.post('http://cwqd.ricecs.cn/admin-api/system/file/upload',
						formData, {
							headers: {
								'Content-Type': 'multipart/form-data',
								'Authorization': 'test1' // 将 Authorization 添加到 headers 中
							}
						});
					console.log(response.data.data, '11111')
					// 文件上传成功后的处理逻辑
					this.$emit('uploadSuccess', {
						name: file.name,
						suffix,
						path: response.data.data,
						thumbnailPath: response.data.data
					})
					console.log('File uploaded successfully:', response.data);
				} catch (error) {
					// 文件上传失败后的处理逻辑
					console.error('Error uploading file:', error);
				} finally {
					this.isUpload = false; // 无论成功或失败，都在最终执行块中重置 isUpload 标志
				}
			},


		},
		beforeDestroy() {
			clearInterval(this.timer)
			this.timer = null
		}
	}
</script>